package cn.codergege.shiro.chapter6.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import cn.codergege.shiro.chapter6.dao.PermissionDao;
import cn.codergege.shiro.chapter6.model.Permission;

@Repository("permissionDao")
public class PermissionDaoImpl implements PermissionDao {
	@Resource
	private JdbcTemplate jdbcTemplate;

	@Override
	public Permission createPermission(Permission permission) throws Exception {
        final String sql = "insert into sys_permissions(permission, description, available) values(?,?,?)";
        /**
         * GeneratedKeyHolder 用来返回新增记录的主键值
         */
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql, new String[] { "id" });
				ps.setString(1, permission.getPermission());
				ps.setString(2, permission.getDescription());
				ps.setBoolean(3, permission.getAvailable());
				return ps;
			}
		}, keyHolder);
        permission.setId(keyHolder.getKey().longValue());
		return permission;
	}

	@Override
	public void deletePermission(Long permissionId) throws Exception {
		// 先删除 sys_roles_permissions 中的关联记录
        String sql = "delete from sys_roles_permissions where permission_id=?";
        jdbcTemplate.update(sql, permissionId);
        
        sql = "delete from sys_permissions where id=?";
        jdbcTemplate.update(sql, permissionId);
	}

}
